package com.tjetc.service.impl;

import com.tjetc.common.JsonResult;
import com.tjetc.dao.CityMapper;
import com.tjetc.entity.City;
import com.tjetc.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CityServiceImpl implements CityService {

    @Value("${token.expiration}")
    private int tokeExpiration;
    @Autowired
    private CityMapper cityMapper;

    @Override
    public JsonResult findCityById(Long id) {
        City city =cityMapper.findCityById(id);
        return JsonResult.success("查找城市成功",city);
    }

    @Override
    public JsonResult getTop(Integer l) {
        List<City> cities=cityMapper.hotcity(l);
        return JsonResult.success("查询成功",cities);
    }

    @Override
    public JsonResult getClazz(Integer classId) {
        List<City> cities=cityMapper.getCityByClazz(classId);
        return JsonResult.success("查询成功",cities);
    }

    @Override
    public JsonResult getCitiesByProvince(Long provinceId) {
        List<City> cities = cityMapper.getCitiesByProvinceOrderByHotness(provinceId);
        return JsonResult.success("查询成功", cities);
    }

    @Scheduled(fixedRate = 86400000) // 每 24 小时执行一次
    @Transactional
    public void updateCityTrends() {

        List<City> cities = cityMapper.selectALL();

        for (City city : cities) {
            String trend = "stable";

            if (city.getLikes() > city.getLastLikes()) {
                trend = "up";
            } else if (city.getLikes() < city.getLastLikes()) {
                trend = "down";
            }

            city.setTrend(trend);
            city.setLastLikes(city.getLikes());

            cityMapper.updateLastLike(city.getId(),city.getLastLikes(),city.getTrend());
        }

    }
}
